package com.huangfu.easysardine.gate.config;

import com.huangfu.easysardine.gate.jwt.JwtAuthenticationTokenFilter;
import com.huangfu.easysardine.gate.service.GateUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created with IntelliJ IDEA.
 * User: huangfu.daohui
 * Date: 2017-8-14
 * Time: 13:47
 * Description:用Spring Security安全配置类，启动加载
 * 集成WebSecurityConfigurerAdapter类重写config
 * 通过 authorizeRequests() 定义哪些URL需要被保护、哪些不需要被保护。
 * 通过 formLogin() 定义当需要用户登录时候，转到的登录页面。
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private GateUserDetailsService detailsService;
    @Value("${gate.ignore.startWith}")
    private String startWith;

    //设置了各种路由访问规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义登录页、登录成功页面、注销页面
        http.formLogin().loginPage("/login").defaultSuccessUrl("/admin/index").permitAll().and()
                .logout().logoutSuccessUrl("/login").invalidateHttpSession(true).and().authorizeRequests()
                // 允许对于网站静态资源的无授权访问
                .antMatchers("/**/*.css", "/img/**", "/**/*.js", "/api/**", "/druid/**") // 放开"/api/**",通过oauth2.0来鉴权
                .permitAll().and().authorizeRequests().antMatchers("/**").authenticated();
        http.csrf().disable();// 由于使用的是JWT，我们这里不需要csrf
        http.headers().frameOptions().disable();
        http.httpBasic();
        // 添加JWT filter
        http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

        // 禁用缓存
        http.headers().cacheControl();
        http.headers().contentTypeOptions().disable();
    }

    //注册了自定义验证组件
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(detailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
        return new JwtAuthenticationTokenFilter();
    }
}
